package jianzhi_offer;

public class _48_把字符串转换成整数 {
    public static void main(String[] args) {
        _48_把字符串转换成整数 test = new _48_把字符串转换成整数();
        System.out.println(test.StrToInt("-18"));
    }

    public int StrToInt(String str) {
        if(str == null || str.trim().equals("")) return 0;
        char[] chars = str.toCharArray();
        boolean flag = true;
        int start = 0;
        if(chars[0] == '-') {
            flag = false;
            if (chars.length == 1) return 0;
            start = 1;
        }else if(chars[0] == '+'){
            if(chars.length == 1) return 0;
            start = 1;
        }
        int[] stack = new int[chars.length-start];
        int index = 0;
        while(start != chars.length) {
            char now  = chars[start++];
            if(!(now >= '0' && now <= '9')) return 0;
            stack[index++] = now-'0';
        }
        int res = 0,radix =1;
        while(index > 0){
            res += stack[--index]*radix;
            radix *= 10;
        }
        if(!flag) res *= -1;
        return res;
    }
}
